
const {connection} = require('./mysql');
const {zentao} = require('../notifier.config.js');

const product = zentao.productId.map(v => `ta.product = ${v}`).join(' OR ');

function getMyBugs(sql) {
    return new Promise(((resolve, reject) => {
        connection.query(sql, function (error, results, fields) {
            if (error) throw error;

            resolve(results);
        });
    }))
}

function getAllActiveBugs() {
    return getMyBugs(`SELECT ta.id, ta.title, ta.product, ta.assignedTo, ta.openedDate, tb.name FROM zt_bug ta LEFT JOIN zt_product tb ON ta.product = tb.id WHERE (${product}) AND ta.status = "active";`);
}
function getNewBugs(date) {
    return getMyBugs(`SELECT ta.id, ta.title, ta.product, ta.assignedTo, ta.openedDate, tb.name FROM zt_bug ta LEFT JOIN zt_product tb ON ta.product = tb.id WHERE (${product}) AND ta.status = "active" AND ta.openedDate > '${date}';`);
}

function searchAllUser() {
    return getMyBugs('SELECT account,realname FROM zt_user;');
}

function searchAllProduct() {
    return getMyBugs('SELECT id,name FROM zt_product;');
}

module.exports = {
    getAllActiveBugs,
    getNewBugs,
    searchAllUser,
    searchAllProduct,
}
